//
//  FNReadFileListVC.m
//  CocoaLumberjackDemo
//
//  Created by ffq on 2023/3/13.
//  Copyright © 2023 shixueqian. All rights reserved.
//

#import "FQReadFileListVC.h"

#import "FQLogManager.h"

#import "FQReadFileDetailsVC.h"

@interface FQReadFileListVC ()<UITableViewDelegate, UITableViewDataSource>

/** <#注释#> */
@property (nonatomic, strong) UITableView *tableView;

/** <#注释#> */
@property (nonatomic, strong) NSMutableArray *datas;

@end

@implementation FQReadFileListVC

#pragma mark - life cycle
- (void)viewDidLoad{
    
    [super viewDidLoad];
    
    [self configNav];
    [self addControllers];
    [self layoutControllers];
    [self configControllers];
    [self initDatas];
    
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    NSString *path = self.datas[indexPath.row];
    
    NSDictionary *fileAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    CGFloat size = [fileAttr fileSize]/1024.0;
    cell.textLabel.text = path.lastPathComponent;
//    cell.textLabel.text = [NSString stringWithFormat:@"%@         %.4f M",path.lastPathComponent,size];
    UILabel *sizeLab = [[UILabel alloc]init];
    sizeLab.font = [UIFont systemFontOfSize:15];
    sizeLab.textColor = UIColor.grayColor;
    sizeLab.text = [NSString stringWithFormat:@"%.2f KB",size];
    [cell addSubview:sizeLab];
    
    sizeLab.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *c1 = [NSLayoutConstraint constraintWithItem:sizeLab attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1 constant:-16];
    NSLayoutConstraint *c2 = [NSLayoutConstraint constraintWithItem:sizeLab attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    [cell addConstraint:c1];
    [cell addConstraint:c2];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FQReadFileDetailsVC *vc = [[FQReadFileDetailsVC alloc]init];
    vc.path = self.datas[indexPath.row];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
   NSString *path = self.datas[indexPath.row];
    
    NSError *err;
    [[NSFileManager defaultManager]removeItemAtPath:path error:&err];
    if(err) {
        FQLog(@"删除失败:%@",err);
        return;
    }
    [self.datas removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
    
}

#pragma mark - CustomDelegate

#pragma mark - event response
- (void)navRightBtnClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要清空所有文件吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self removeAllFiles];
    }];
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alert addAction:cancelBtn];
    [alert addAction:okBtn];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)navBackBtnClick {
    if (self.navigationController && self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)removeAllFiles {
    
    NSString *fileDicPath = [[FQLogManager sharedInstance]defaultLogsDirectory];
    NSError *err;
    [[NSFileManager defaultManager]removeItemAtPath:fileDicPath error:&err];
    if(err) {
        FQLog(@"删除失败:%@",err);
    }
    
    [self initDatas];
}

#pragma mark - private methods

#pragma mark - private init methods

- (void)configNav{
    self.title = @"日志文件列表";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"清空" style:UIBarButtonItemStylePlain target:self action:@selector(navRightBtnClick)];
    
    if (@available(iOS 13.0, *)) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemClose target:self action:@selector(navBackBtnClick)];
    } else {
        // Fallback on earlier versions
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(navBackBtnClick)];
    }
    
}

- (void)addControllers{
    [self.view addSubview:self.tableView];
}

- (void)layoutControllers{
    
}
- (void)configControllers{
    
}

- (void)initDatas{
    self.datas = [[FQLogManager sharedInstance] filePaths].mutableCopy;
    [self.tableView reloadData];
}

#pragma mark - getters setters
- (UITableView *)tableView {
    
    if(!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.frame];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
@end
